﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CSP.Common.Web;
using CSP.Model.CSPEnum;
using CSP.Model.CSP;
using CSP.Bll;
using CSP.Bll.IObjectBlls;
using CSP.Common.Tools;

namespace CSP.Web.MyHome.ServiceOrder
{
    public partial class List : CSPMyHome
    {
        private List<string> _searchOrderNumbers;
        private List<string> SearchOrderNumbers
        {
            get
            {
                return ViewState[SEARCHIDSKEY] as List<string>;

            }
            set
            {
                ViewState[SEARCHIDSKEY] = _searchOrderNumbers = value;
            }
        }

        private const string SEARCHIDSKEY = "searchids";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //取消订单
                if (Request["cancelordernumber"] != null)
                {
                    string orderNumber = Request["cancelordernumber"].ToString();
                    string jsonResult = CancelOrder(orderNumber);
                    Response.Clear();
                    Response.Write(jsonResult);
                    Response.End();
                }
                //确认订单
                else if (Request["confirmordernumber"] != null)
                {
                    string orderNumber = Request["confirmordernumber"].ToString();
                    DateTime confirmStartDate = Convert.ToDateTime(Request["startdate"].ToString());
                    DateTime confirmEndDate = Convert.ToDateTime(Request["enddate"].ToString());
                    string jsonResult = ConfirmOrder(orderNumber, confirmStartDate, confirmEndDate);
                    Response.Clear();
                    Response.Write(jsonResult);
                    Response.End();
                }
                //正常访问
                else
                {
                    InitConsumeOrderList();
                }
            }
        }


        /// <summary>
        /// 初始化参数
        /// </summary>
        private void InitParm()
        {
            this.S_OrderStatus.SelectedIndex = 0;
            this.S_OrderTimeRegion.SelectedIndex = 0;
            SetPagerParm(0, 15, SearchOrderNumbers.Count);
        }

        protected void S_OrderTimeRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            DateTime startDate;
            DateTime endDate;
            //一个月内的合作
            if (this.S_OrderTimeRegion.SelectedValue == "0")
            {
                startDate = DateTime.Now.AddMonths(-1).AddDays(-1);
                endDate = DateTime.Now;
            }
            //三个月内的合作
            else if (this.S_OrderTimeRegion.SelectedValue == "1")
            {
                startDate = DateTime.Now.AddMonths(-3).AddDays(-1);
                endDate = DateTime.Now;
            }
            //一年内的合作
            else
            {
                startDate = DateTime.Now.AddYears(-1).AddDays(-1);
                endDate = DateTime.Now;
            }
            List<string> searchIds = FindIdsByOrderTimeRegion(startDate, endDate);
            SearchOrderNumbers = searchIds;
            InitParm();
            ICollection<Order> orders = GetOrdersByOrderNumbers(searchIds, 0, U_OrderPager.PageSize);
            BindListUI(orders);
        }

        protected void S_OrderStatus_SelectedIndexChanged(object sender, EventArgs e)
        {

            //全部
            if (this.S_OrderStatus.SelectedValue == "")
            {
                InitConsumeOrderList();
                return;
            }

            OrderStatus orderStatus = (OrderStatus)Convert.ToInt32(this.S_OrderStatus.SelectedValue);
            List<string> searchOrderNumbers = FindIdsByOrderStatus(orderStatus);
            SearchOrderNumbers = searchOrderNumbers;
            InitParm();
            ICollection<Order> orders = GetOrdersByOrderNumbers(searchOrderNumbers, 0, U_OrderPager.PageSize);
            BindListUI(orders);
        }

        protected void Btn_Search_Click(object sender, EventArgs e)
        {

            List<string> searchOrderNumbers = new List<string>();
            if (Txt_SearchValue.Value.Trim() == "")
            {
                InitConsumeOrderList();
                return;
            }
            else
            {
                SearchOrderNumbers = searchOrderNumbers = FindIdsBySearchValue();
            }
            InitParm();
            ICollection<Order> orders = GetOrdersByOrderNumbers(searchOrderNumbers, 0, searchOrderNumbers.Count);
            BindListUI(orders);
        }

        protected void U_OrderPager_IndexChange(object sender, EventArgs e)
        {
            ICollection<Order> orders = GetOrdersByOrderNumbers(SearchOrderNumbers, U_OrderPager.PageIndex, U_OrderPager.PageSize);
            BindListUI(orders);
        }

        /// <summary>
        /// 根据订单状态获取订单名称
        /// </summary>
        /// <param name="orderStatus"></param>
        /// <returns></returns>
        protected string GetNameByOrderStatus(string orderStatus)
        {
            string result = "";
            if ((OrderStatus)Convert.ToInt32(orderStatus) == OrderStatus.Waiting)
            {
                result = "预约中";
            }
            else if ((OrderStatus)Convert.ToInt32(orderStatus) == OrderStatus.Canceled)
            {
                result = "订单取消";
            }
            else if ((OrderStatus)Convert.ToInt32(orderStatus) == OrderStatus.ServiceConfirm)
            {
                result = "等待消费者确认";
            }
            else if ((OrderStatus)Convert.ToInt32(orderStatus) == OrderStatus.ConsumeConfirm)
            {
                result = "预约成功";
            }
            return result;
        }

        protected string GetCreditImgNameByUserName(string userName)
        {
            int code = GetUserCredit(userName);
            return GetConsumptionCreditGrade(code);
        }

        /// <summary>
        /// 设置分页参数
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        private void SetPagerParm(int pageIndex, int pageSize, int pageCount)
        {
            this.U_OrderPager.PageSize = pageSize;
            this.U_OrderPager.PageIndex = pageIndex;
            this.U_OrderPager.ItemCount = pageCount;
        }

        /// <summary>
        /// 初始化消费订单列表
        /// </summary>
        private void InitConsumeOrderList()
        {

            List<string> searchOrderNumbers = FindIdsByUser();
            SearchOrderNumbers = searchOrderNumbers;

            InitParm();
            ICollection<Order> orders = GetOrdersByOrderNumbers(searchOrderNumbers, 0, U_OrderPager.PageSize);
            BindListUI(orders);
        }

        /// <summary>
        /// 绑定控件
        /// </summary>
        /// <param name="orders"></param>
        private void BindListUI(ICollection<Order> orders)
        {
            R_ConsumeOrder.DataSource = orders;
            R_ConsumeOrder.DataBind();
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <returns></returns>
        private string CancelOrder(string orderNumber)
        {

            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();
            Order order = null;
            try
            {
                using (IOrderBll orderBll = bllFactory.GetOrderBll())
                {
                    order = orderBll.CancelOrderAsService(orderNumber, UserProvider.UserName);
                }
            }
            catch (Exception ex)
            {
                LoggerProvider.Error(orderNumber, ex);
                return "{\"status\":0,\"msg\":\"订单取消失败!\"}";
            }

            if (order == null)
            {
                return "{\"status\":2,\"msg\":\"权限不足!\"}";
            }

            return "{\"status\":1,\"msg\":\"订单取消成功!\"}"; ;
        }

        private string ConfirmOrder(string orderNumber, DateTime confirmStartDate, DateTime confirmEndDate)
        {

            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();
            Order order = null;
            try
            {
                using (IOrderBll orderBll = bllFactory.GetOrderBll())
                {
                    order = orderBll.ConfirmOrderAsService(orderNumber, UserProvider.UserName, confirmStartDate, confirmEndDate);
                }
            }
            catch (Exception ex)
            {
                LoggerProvider.Error(orderNumber, ex);
                return "{\"status\":0,\"msg\":\"订单取消失败!\"}";
            }

            if (order == null)
            {
                return "{\"status\":2,\"msg\":\"权限不足!\"}";
            }

            return "{\"status\":1,\"msg\":\"订单已经确认预约完成!\"}";
        }

        /// <summary>
        /// 根据UserName获取消费者Id 信息；
        /// </summary>
        /// <returns></returns>
        private List<string> GetIdsByUserName()
        {
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();
            List<string> ids = new List<string>();

            using (IOrderBll serviceInfoBll = bllFactory.GetOrderBll())
            {
                ids = serviceInfoBll.FindOrderNumbersByServiceUser(UserProvider.UserName);
            }

            return ids;
        }

        /// <summary>
        /// 根据订单状态获取订单Ids
        /// </summary>
        /// <param name="orderStatus"></param>
        /// <returns></returns>
        private List<string> FindIdsByOrderStatus(OrderStatus orderStatus)
        {
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();
            List<string> ids = new List<string>();

            using (IOrderBll orderBll = bllFactory.GetOrderBll())
            {
                ids = orderBll.FindOrderNumbersByServiceUserAndStatus(UserProvider.UserName, orderStatus);
            }

            return ids;
        }

        private List<string> FindIdsByOrderTimeRegion(DateTime startDate, DateTime endDate)
        {
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();
            List<string> ids = new List<string>();

            using (IOrderBll serviceInfoBll = bllFactory.GetOrderBll())
            {
                ids = serviceInfoBll.FindOrderNumbersByServiceUserNameAndStartTimeAndEndTime(UserProvider.UserName, startDate, endDate);
            }

            return ids;
        }

        /// <summary>
        /// 根据用户信息获取Ids
        /// </summary>
        private List<string> FindIdsByUser()
        {
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();
            List<string> ids = new List<string>();

            using (IOrderBll serviceInfoBll = bllFactory.GetOrderBll())
            {
                ids = serviceInfoBll.FindOrderNumbersByServiceUser(UserProvider.UserName);
            }

            return ids;
        }

        /// <summary>
        /// 根据SearchValue获取结果ID
        /// </summary>
        /// <returns></returns>
        private List<string> FindIdsBySearchValue()
        {
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();

            List<string> orderNumbers = new List<string>();
            using (IOrderBll orderBll = bllFactory.GetOrderBll())
            {
                orderNumbers = orderBll.FindByServiceUserAndSearchValue(UserProvider.UserName, Txt_SearchValue.Value.Trim());
            }
            return orderNumbers;
        }


        /// <summary>
        /// 获取用户信誉度对象
        /// </summary>
        /// <returns></returns>
        private int GetUserCredit(string userName)
        {
            UserCredit result = null;
            using (var userCreditBll = CSPBllFactory.GetInstance().GetUserCreditBll())
            {
                result = userCreditBll.GetByUser(userName);
            }

            if (result!=null)
            {
                return result.ServiceCredit; 
            }
            return 0;
        }

        /// <summary>
        /// 获取服务等级
        /// </summary>
        /// <param name="score"></param>
        /// <returns></returns>
        private string GetConsumptionCreditGrade(int score)
        {
            return CommonTool.GetConsumptionCreditGradeByScore(score);
        }

        /// <summary>
        /// 是否显示"取消订单"
        /// </summary>
        /// <returns></returns>
        protected bool IsShowCancelOrder(int remindStatus)
        {
            bool result = false;
            //如果需要服务者合作确认
            if ((OrderRemindStatus)remindStatus == OrderRemindStatus.ServiceCooperationConfirm)
            {
                result = true;
            }
            else
            {
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 是否显示操作
        /// </summary>
        /// <param name="orderStatus"></param>
        /// <returns></returns>
        protected bool IsShowOperate(int orderStatus)
        {
            bool result = false;

            if ((OrderStatus)orderStatus != OrderStatus.Canceled)
            {
                result = true;
            }
            return result;
        }

        /// <summary>
        /// 是否显示确认按钮
        /// </summary>
        /// <param name="remindStatus"></param>
        /// <returns></returns>
        protected bool IsShowCooperationConfirm(int remindStatus)
        {
            bool result = false;
            //如果需要服务者合作确认
            if ((OrderRemindStatus)remindStatus == OrderRemindStatus.ServiceCooperationConfirm)
            {
                result = true;
            }
            else
            {
                result = false;
            }
            return result;

        }

        /// <summary>
        /// 是否显示评价
        /// </summary>
        /// <returns></returns>
        protected bool IsShowRate(int remindStatus)
        {
            bool result = false;
            //如果双方待评价
            if ((OrderRemindStatus)remindStatus == OrderRemindStatus.RatingBoth)
            {
                result = true;
            }
            //如果需要消费者合作确认
            else if ((OrderRemindStatus)remindStatus == OrderRemindStatus.RatingConsume)
            {
                result = true;
            }
            else
            {
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 根据分页信息和Ids获取Orders订单信息
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageCount"></param>
        /// <returns></returns>
        private ICollection<Order> GetOrdersByOrderNumbers(List<string> ids, int pageIndex, int pageCount)
        {
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();
            ICollection<Order> result = new List<Order>();
            using (IOrderBll orderBll = bllFactory.GetOrderBll())
            {
                result = orderBll.GetByOrderNumbers(ids, pageIndex, pageCount);
            }
            return result;
        }
    }
}